package com.bookstore.controller;//package com.bookstore.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bookstore.entity.Book;
import com.bookstore.entity.User;
import com.bookstore.service.BookService;
import com.bookstore.service.DownloadService;
import com.bookstore.utils.FileUpload;
import com.bookstore.utils.Json;
import com.bookstore.utils.States;
import com.bookstore.utils.StringUtil;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;

@Controller
public class BookController {

    private final Logger logger = LoggerFactory.getLogger(BookController.class);

    @Autowired
    BookService bookService;

    @Autowired
    private DownloadService downloadService;

    /**
     * 分页获取所有的图书数据
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get_book_by_page", method = RequestMethod.GET)
    public Json getBookByPage(@RequestParam("pageNum") String pageNum, @RequestParam("pageSize") String pageSize) {
        Json json = new Json();
        if (!StringUtils.isEmpty(pageNum) && !StringUtils.isEmpty(pageSize)) {
            if (StringUtil.isInteger(pageNum) && StringUtil.isInteger(pageSize)) {
                PageInfo<Book> bookPageInfo = bookService.getBookByPage(Integer.valueOf(pageNum), Integer.valueOf(pageSize));
                bookPageInfo.setPrePage(Integer.parseInt(pageNum));
                bookPageInfo.setPageSize(Integer.parseInt(pageSize));
                if (Integer.parseInt(pageNum) == 1) {
                    bookPageInfo.setIsFirstPage(true);
                } else {
                    bookPageInfo.setIsFirstPage(false);
                }
                json.setObj(bookPageInfo);
                json.setMsg("数据获取成功");
                json.setSuccess(true);
                return json;
            } else {
                json.setMsg(States.REQUEST_ERROR_CONDITION02.getMsg());
                json.setSuccess(false);
                return json;
            }
        } else {
            json.setMsg(States.REQUEST_ERROR_CONDITION01.getMsg());
            json.setSuccess(false);
            return json;
        }
    }

    /**
     * 获取前十个图书数据
     *
     * @return
     */
    @RequestMapping(value = "/getBookTop", method = RequestMethod.GET, produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String getBookTop() {
        JSON json = new JSONArray();
        List<Book> books = bookService.getBookTop();
        return json.toJSONString(books);
    }

    /**
     * 增加图书
     *
     * @param typeId
     * @param bookImg
     * @param bookName
     * @param bookAuthor
     * @param bookDetails
     * @param bookURL
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/add_book", method = RequestMethod.POST)
    @ResponseBody
    public String addBook(@RequestParam("typeId") Long typeId, @RequestParam("bookImg") MultipartFile bookImg, @RequestParam("bookName") String bookName,
                          @RequestParam("bookAuthor") String bookAuthor, @RequestParam("bookDetails") String bookDetails, @RequestParam("book_file") MultipartFile bookURL, HttpServletRequest request) throws IOException {
        JSON json = new JSONArray();
        System.out.println("添加图书");
        User user = (User) request.getSession().getAttribute(LoginAndRegisterController.USER);
        String filename = bookURL.getOriginalFilename();
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);
        System.out.println("user:"+user.getuId()+"姓名"+user.getAccount());
        if (user != null) {
            String download = FileUpload.uploadPDF(bookURL, request);
            if (!StringUtils.isEmpty(download)) {
                String img = FileUpload.uploadImg(bookImg, request);
                if (!StringUtils.isEmpty(img)) {
                    if (!StringUtils.isEmpty(typeId) && !StringUtils.isEmpty(bookName) && !StringUtils.isEmpty(bookAuthor)) {
                        Book book = new Book();
                        book.setTotalScore((double)0);
                        book.setScoreNumber((long)0);
                        book.setScore((double) 0);
                        book.setDownloadNumber((short)0);
                        book.setDownload(download);
                        book.setUploadUser(user.getuId());
                        book.setBookName(bookName);
                        book.setTypeId(typeId);
                        book.setBookImg(img);
                        book.setBookId(StringUtil.getUUID());
                        book.setBookAnthou(bookAuthor);
                        book.setBookDetails(bookDetails);
                        book.setUploadDate(new Date());
                        book.setFormat(prefix);
                        int insert = bookService.insertSelective(book);
                        if (insert > 0) {
                            return json.toJSONString(States.REQUEST_UPDATE_SUCCESS);
                        } else {
                            return json.toJSONString(States.REQUEST_UPDATE_FILED);
                        }
                    } else {
                        return json.toJSONString(States.REQUEST_ERROR_CONDITION01);
                    }
                } else {
                    return json.toJSONString(States.REQUEST_ERROR_UPLOAD_IMG);
                }
            } else {
                return json.toJSONString(States.REQUEST_ERROR_UPLOAD_PDF);
            }
        } else {
            return json.toJSONString(States.REQUEST_ERROR_NOLOGIN);
        }
    }

    @RequestMapping(value = "/del_book", method = RequestMethod.POST)
    public String delBook(@RequestParam("bookID") String bookID) {
        if (!StringUtils.isEmpty(bookID)) {
            int del = bookService.delBook(bookID);
            if (del > 0) {
                return JSON.toJSONString(States.REQUEST_DEL_SUCCESS);
            } else {
                return JSON.toJSONString(States.REQUEST_DEL_FILED);
            }
        } else {
            return JSON.toJSONString(States.REQUEST_ERROR_CONDITION01);
        }
    }

    /**
     * 更新图书
     * @param typeId
     * @param bookImg
     * @param bookName
     * @param bookAuthor
     * @param bookDetails
     * @param bookURL
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/update_book", method = RequestMethod.POST)
    public String updateBook(@RequestParam("typeId") Long typeId, @RequestParam("bookImg") MultipartFile bookImg, @RequestParam("bookName") String bookName,
                             @RequestParam("bookAuthor") String bookAuthor, @RequestParam("bookDetails") String bookDetails, @RequestParam("book_file") MultipartFile bookURL,@RequestParam("book_id")String bookId, HttpServletRequest request) throws IOException {
        JSON json = new JSONArray();
        User user = (User) request.getSession().getAttribute(LoginAndRegisterController.USER);
        System.out.println("user:" + user.getuId() + "姓名" + user.getAccount());
        if (user != null) {
            if (!StringUtils.isEmpty(typeId) && !StringUtils.isEmpty(bookName) && !StringUtils.isEmpty(bookAuthor) && !StringUtils.isEmpty(bookId)) {
                Book book = new Book();
                if (bookURL!=null){
                   String upload =  FileUpload.uploadPDF(bookURL,request);
                    book.setDownload(upload);
                }
                if (bookImg!=null){
                    String img = FileUpload.uploadImg(bookImg,request);
                    book.setBookImg(img);
                }
                book.setBookId(bookId);
                book.setBookName(bookName);
                book.setTypeId(typeId);
                book.setBookAnthou(bookAuthor);
                book.setBookDetails(bookDetails);
                int updateBook = bookService.updateBook(book);
                if (updateBook > 0) {
                    return json.toJSONString(States.REQUEST_UPDATE_SUCCESS);
                } else {
                    return json.toJSONString(States.REQUEST_UPDATE_FILED);
                }
            } else {
                return json.toJSONString(States.REQUEST_ERROR_CONDITION01);
            }
        } else {
            return json.toJSONString(States.REQUEST_ERROR_UPLOAD_IMG);

        }
    }

    /**
     * 根据图书的类型来查找数据
     *
     * @param pageNum
     * @param pageSize
     * @param typeID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get_book_by_type", method = RequestMethod.GET, produces = "text/html; charset=UTF-8")
    public String getBookByType(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, @RequestParam("typeID") Long typeID) {
        JSONObject jsonObjectServer = new JSONObject();
        PageInfo<Book> bookPageInfo = null;
        if (typeID <= 6) {
            bookPageInfo = bookService.getBookByParentCategory(Integer.valueOf(pageNum), Integer.valueOf(pageSize), typeID);
        } else {
            bookPageInfo = bookService.getBookByCategory(Integer.valueOf(pageNum), Integer.valueOf(pageSize), typeID);
        }
        return jsonObjectServer.toJSONString(bookPageInfo);
    }

    /**
     * 根据输入框的数据进行模糊查询
     *
     * @param bookName
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get_book_by_name_author", method = RequestMethod.GET)
    public Json getBookByName(@RequestParam("bookName") String bookName, @RequestParam("pageNum") String pageNum, @RequestParam("pageSize") String pageSize) throws UnsupportedEncodingException {
        System.out.println(bookName);
        Json json = new Json();
        if (!StringUtils.isEmpty(bookName) && !StringUtils.isEmpty(pageNum) && !StringUtils.isEmpty(pageSize)) {
            if (StringUtil.isInteger(pageNum) && StringUtil.isInteger(pageSize)) {
                PageInfo<Book> bookPageInfo = bookService.getBookByName(bookName, Integer.valueOf(pageNum), Integer.valueOf(pageSize));
                json.setSuccess(true);
                json.setObj(bookPageInfo);
                json.setMsg("获取数据成功");
                return json;
            } else {
                json.setSuccess(false);
                json.setMsg("参数格式出错");
                return json;
            }
        } else {
            json.setSuccess(false);
            json.setMsg("参数不能为空");
            return json;
        }
    }

    /**
     * 根据排序字段获取前十条信息
     *
     * @param fliedName 排序字段
     * @return
     */
    @RequestMapping(value = "/getTopBook", method = RequestMethod.GET, produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String getTop10BookByFliedName(@RequestParam("fliedName") String fliedName) {
        if (fliedName.equals("SCORE") || fliedName.equals("UPLOAD_DATE") || fliedName.equals("DOWNLOAD_NUMBER")) {
            List<Book> bookList = bookService.getTop10BookByFliedName(fliedName);
            System.out.println(bookList.get(0).getUploadDate());
            return JSON.toJSONString(bookList);
        } else {
            return "你查询排序的字段名不正确";
        }
    }

    /**
     * 根据图书Id跳转到对应的图书界面
     *
     * @param bookId
     * @param request
     * @return
     */
    @RequestMapping(value = "/into_bookInfo", method = RequestMethod.GET)
    public String getBookById(@RequestParam("bookId") String bookId, HttpServletRequest request) {
        Book book = bookService.getBookById(bookId);
        if (book != null) {
            request.setAttribute("book", book);
            System.out.println("图书简介"+book.getBookDetails());
            return "jsp/bookinfo";
        } else {
            return "jsp/error";
        }
    }

    /**
     * 根据每个人的登陆获取对应的推荐图书
     * @param request
     * @return
     */
    @RequestMapping(value = "/get_book_by_cf",method = RequestMethod.GET,produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String getBookByCf(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute(LoginAndRegisterController.USER);
        PageInfo<Book> bookPageInfo = bookService.getBookByCf(user.getuId());
        System.out.println(bookPageInfo.getList().size());
        if (bookPageInfo.getList().size()<1){
            List<Book> book = bookService.getTop10BookByFliedName("SCORE");
            bookPageInfo.setList(book);
        }

        return JSON.toJSONString(bookPageInfo);
    }

    @ResponseBody
    @RequestMapping(value = "/get_modify_message",method = RequestMethod.GET)
    public Json getModifyMessage(@RequestParam("bookId")String bookId){
        Json json = new Json();
        if (!StringUtils.isEmpty(bookId)){
            Book book = bookService.getModifyMessage(bookId);
            json.setSuccess(true);
            json.setMsg("获取成功");
            json.setObj(book);
            return json;
        }else{
            json.setMsg("参数错误，该参数没有数据！");
            json.setSuccess(false);
            return json;
        }
    }

    /**
          * 用户下载书籍
          * @param bId 图书的id
          * @param response
          * @param request
          */
    @RequestMapping(value = "/user/download_book",method = RequestMethod.GET,produces = "text/html; charset=UTF-8")
    public void download(@RequestParam("b_id") String bId, HttpServletResponse response, HttpServletRequest request) {
                response.setContentType("multipart/form-data");
                System.out.println(bId);
                Book book = bookService.getBookById(bId);
                System.out.println(book.getDownload());
                String savePath = request.getSession().getServletContext().getRealPath("/upload/")+ book.getDownload();
                System.out.println(savePath);
                File file = new File(savePath);
                if (!file.exists()) {
                        System.out.println("该图书不存在");
                        return;
                    }
                OutputStream output = null;
                try {
                        // 清空response
                                response.reset();
                        //设置返回响应头
                     response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(file.getName().getBytes("gbk"),"iso-8859-1")  + "\"");
                        response.addHeader("Content-Length", "" + file.length());
                        response.setContentType("application/octet-stream;charset=UTF-8");
                        output = response.getOutputStream();
                        FileInputStream input = new FileInputStream(file);
                        byte[] buf = new byte[1024];
                        int numBytesRead = 0;
                        while ((numBytesRead = input.read(buf)) != -1) {
                                output.write(buf, 0, numBytesRead);
                            }
                        input.close();
                        output.flush();
                        output.close();
                        //添加用户的下载记录
                        User user = (User) request.getSession().getAttribute(LoginAndRegisterController.USER);
                        downloadService.addDownloadRecord(user.getuId(),book.getBookId());
                    } catch (IOException e) {
                        logger.error(e.toString());
                    }

                 }
}
